package com.databasefunction;

import java.sql.*;

public class DatabaseConnection {
 // JDBC driver name and database URL

 
 Statement stmt = null;
 
 
public Connection getConnection(String dbname) {
	Connection connection = null;
	String finalURL = null;
	
	
	if (dbname!=null) {
		
		finalURL = DatabaseConstants.DB_URL+dbname;
		
	}else{
		
		finalURL = DatabaseConstants.DB_URL;
	}
	try {
		Class.forName("com.mysql.jdbc.Driver");
	
		 System.out.println("Connecting to database..."+DatabaseConstants.DB_URL);
	      connection = DriverManager.getConnection(finalURL, DatabaseConstants.USER, DatabaseConstants.PASS);

	  } catch (ClassNotFoundException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (SQLException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}

      //STEP 3: Open a connection
     
	return connection;	
}


public void createDatabase(Connection connection){
	
	try{
	      //STEP 2: Register JDBC driver
	    
	      //STEP 4: Execute a query
	      System.out.println("Creating database...");
	      stmt = connection.createStatement();
	      
	      String sql = "CREATE DATABASE IF NOT EXISTS parvati_database";
	      stmt.executeUpdate(sql);
	      System.out.println("Database created successfully...");
	   }catch(SQLException se){
	      //Handle errors for JDBC
	      se.printStackTrace();
	   }catch(Exception e){
	      //Handle errors for Class.forName
	      e.printStackTrace();
	   }finally{
	      //finally block used to close resources
	     
	   }//end try
	
}


public void selectDatabase(Connection connection){
	
	
	try{
	      //STEP 2: Register JDBC driver
	    

	      //STEP 3: Open a connection
	      System.out.println("Connecting to a selected database...");
	      connection = DriverManager.getConnection(DatabaseConstants.DB_URL, DatabaseConstants.USER, DatabaseConstants.PASS);
	      System.out.println("Connected database successfully...");
	   }catch(SQLException se){
	      //Handle errors for JDBC
	      se.printStackTrace();
	   }catch(Exception e){
	      //Handle errors for Class.forName
	      e.printStackTrace();
	   }finally{
	      //finally block used to close resources
	      //end finally try
	   }//end try
	
}

 
 
 
}